package org.lewis.common.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.lewis.common.Constants;
import org.lewis.common.domain.User;

import com.tocersoft.framework.web.ActionContext;

public class WebUtils {

	/**
	 * 获取物理路径
	 * 
	 * @param path
	 *            相对路径
	 * @return 物理路径
	 */
	public static String getRealyPath(String path) {
		return getSession().getServletContext().getRealPath(path).replace("\\",
				"/");
	}

	public static User getCurrentUser() {
		return (User) getSession().getAttribute(Constants.CURRENTUSER);
	}

	public static void modifyCurrentUser(User user) {
		getSession().setAttribute(Constants.CURRENTUSER, user);
	}

	public static boolean isPost() {
		HttpServletRequest request = ActionContext.getActionContext()
				.getHttpServletRequest();
		if ("POST".equals(request.getMethod())) {
			return true;
		}
		return false;
	}

	public static HttpServletRequest getRequest() {
		return ActionContext.getActionContext().getHttpServletRequest();
	}

	public static HttpServletResponse getResponse() {
		return ActionContext.getActionContext().getHttpServletResponse();
	}

	public static HttpSession getSession() {
		return ActionContext.getActionContext().getHttpSession();
	}

	public static String getParameter(String name) {
		return getRequest().getParameter(name);
	}

	/**
	 * 获得IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr() {
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		} else {
			return ip;
		}
		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		} else {
			int index = ip.indexOf(',');
			if (index != -1) {
				ip = ip.substring(0, index);
			}
		}
		return ip;
	}

	/**
	 * 过滤html尖括号
	 * 
	 * @param target
	 * @return
	 */
	public static String safe(String target) {
		target = target.replaceAll("<", "&lt;");
		target = target.replaceAll(">", "&gt;");
		return target;
	}

}
